package org.inasnet;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

import org.inasnet.util.Util;

/**
 * Shell over standard map< String >.
 * Added loading files, consists of basic String constants.
 */
public class StringMap 
{
	public StringMap()
	{
	}
	
	public void loadAsConfigFormatFromFile( String filename )
	{
		loadAsConfigFormat( Util.loadFile( filename ) );
	}
	
	public void loadAsConfigFormat( String parse )
	{
		if( ! mMap.isEmpty() )
		{
			mMap.clear();
		}
		
		int state = 0;
		
		String key   = new String();
		String value = new String();
		
		int readIter = 0;
		
		while( true )
		{
			switch( state )
			{
			case 0: // read key
				if( parse.charAt( readIter ) != ' ' )
				{
					if( parse.charAt( readIter ) == '\r' )
					{
						readIter++;
					}
					else
					{
						key += parse.charAt( readIter );
					}
				}
				else
				{
					while( parse.charAt( readIter ) == ' '  )
					{
						readIter++;
						
						if( readIter == parse.length() )
						{
							break;
						}
					}
					readIter--;
					
					state = 1;
				}
				break;
				
			case 1: // read value after ' '
				if( parse.charAt( readIter ) != '\r' )
				{
					value += parse.charAt( readIter );
				}
				else
				{
					if( key.length() > 0 && value.length() > 0 )
						add( key, value );
					
					readIter++;
					
					key   = new String();
					value = new String();
					
					state = 0;
				}
				break;
			}
			
			readIter++;
			
			if( readIter == parse.length() )
			{
				break;
			}
		}
		
		if( key.length() > 0 && value.length() > 0 )
			add( key, value );
	}
	
	public void add( String key, String value )
	{
		mMap.put( key, value );
	}
	
	public String get( String key ) throws Exception
	{
		String value = mMap.get( key );
		
		if( value == null )
		{
			throw new Exception( "No data found `" + key + "`!" );
		}
		
		return value;
	}
	
	public void set( String key, String parameter )
	{
		mMap.put( key, parameter );
	}
	
	public Set< Entry< String, String > > getValues()
	{
		return mMap.entrySet();
	}
	
	Map< String, String > mMap = new HashMap< String, String >();
}
